<template>
  <div class="app-container" :key="componentKey">
    <!-- 搜索表单区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 合同编号搜索 -->
      <el-form-item label="合同编号" prop="contractNo">
        <el-input
          v-model="queryParams.contractNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>

      <!-- 老人姓名搜索 -->
      <el-form-item label="老人姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>
      
      <!-- 老人身份证号搜索 -->
      <el-form-item label="老人身份证号" prop="idCard">
        <el-input
          v-model="queryParams.idCard"
          placeholder="请输入老人身份证号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 280px"
        />
      </el-form-item>
      
      <!-- 入住时间范围搜索 -->
      <el-form-item label="入住时间" style="width: 380px">
        <el-date-picker
          v-model="daterangeCheckInStartTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      
      <!-- 搜索操作按钮 -->
      <el-form-item>
        <el-button icon="Refresh" @click="resetQuery" style="margin-left: 30px;">重置</el-button>
        <el-button type="primary" icon="Search" @click="handleQuery" style="margin-left: 30px;">搜索</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 发起入住申请按钮 -->
    <el-button type="primary" @click="goToCheckInForm" style="float: right;">发起入住申请</el-button>
    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <!-- 新增按钮 -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:management:add']"
        >新增</el-button>
      </el-col>
      
      <!-- 修改按钮 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:management:edit']"
        >修改</el-button>
      </el-col>
      
      <!-- 删除按钮 -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:management:remove']"
        >删除</el-button>
      </el-col>
      
      <!-- 导出按钮 -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:management:export']"
        >导出</el-button>
      </el-col>
      
      <!-- 手动刷新按钮 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Refresh"
          @click="handleRefresh"
        >刷新</el-button>
      </el-col>
      
      <!-- 右侧工具栏 -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="managementList" @selection-change="handleSelectionChange">
      <!-- 多选框列 -->
      <el-table-column type="selection" width="50" align="center" />
      
      <!-- 序号列 -->
      <el-table-column label="序号" type="index" width="50" align="center" />
      
      <!-- 合同编号列 -->
      <el-table-column label="合同编号" align="center" prop="contract.contractNo" width="200" />
      
      <!-- 老人姓名列 -->
      <el-table-column label="老人姓名" align="center" prop="elderly.name" width="120" />
      
      <!-- 老人身份证号列 -->
      <el-table-column label="老人身份证号" align="center" prop="elderly.idCard" width="200" />
      
      <!-- 入住床位列 -->
      <el-table-column label="入住床位" align="center" prop="bed.bedNo" width="100" />
      
      <!-- 合同开始时间列 -->
      <el-table-column label="合同开始时间" align="center" prop="contract.startDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.contract?.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      
      <!-- 合同结束时间列 -->
      <el-table-column label="合同结束时间" align="center" prop="contract.endDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.contract?.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      
      <!-- 创建人列 -->
      <el-table-column label="创建人" align="center" prop="sysUser.nickName" width="100" />
      
      <!-- 创建时间列 -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:management:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:management:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入住管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="managementRef" :model="form" :rules="rules" label-width="80px">
        <!-- 基本信息 -->
        <el-form-item label="单据编号" prop="checkInNo">
          <el-input v-model="form.checkInNo" placeholder="请输入单据编号" />
        </el-form-item>
        
        <el-form-item label="老人外键编号" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键编号" />
        </el-form-item>
        
        <!-- 时间信息 -->
        <el-form-item label="入住开始时间" prop="checkInStartTime">
          <el-date-picker clearable
            v-model="form.checkInStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入住开始时间">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="入住预结束时间" prop="checkInEndTime">
          <el-date-picker clearable
            v-model="form.checkInEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择入住预结束时间">
          </el-date-picker>
        </el-form-item>
        
        <!-- 创建人信息 -->
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        
        <!-- 关联信息 -->
        <el-form-item label="护理等级外键编号" prop="nursingLevelId">
          <el-input v-model="form.nursingLevelId" placeholder="请输入护理等级外键编号" />
        </el-form-item>
        
        <el-form-item label="入住床位外键编号" prop="bedId">
          <el-input v-model="form.bedId" placeholder="请输入入住床位外键编号" />
        </el-form-item>
        
        <!-- 费用期限 -->
        <el-form-item label="费用期限开始时间" prop="feeStartDate">
          <el-date-picker clearable
            v-model="form.feeStartDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择费用期限开始时间">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="费用期限结束时间" prop="feeEndDate">
          <el-date-picker clearable
            v-model="form.feeEndDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择费用期限结束时间">
          </el-date-picker>
        </el-form-item>
        
        <!-- 费用信息 -->
        <el-form-item label="押金" prop="deposit">
          <el-input v-model="form.deposit" placeholder="请输入押金" />
        </el-form-item>
        
        <el-form-item label="护理费用" prop="nursingFee">
          <el-input v-model="form.nursingFee" placeholder="请输入护理费用" />
        </el-form-item>
        
        <el-form-item label="床位费用" prop="bedFee">
          <el-input v-model="form.bedFee" placeholder="请输入床位费用" />
        </el-form-item>
        
        <el-form-item label="其他费用" prop="otherFee">
          <el-input v-model="form.otherFee" placeholder="请输入其他费用" />
        </el-form-item>
        
        <el-form-item label="医保支付" prop="medicalInsurancePayment">
          <el-input v-model="form.medicalInsurancePayment" placeholder="请输入医保支付" />
        </el-form-item>
        
        <el-form-item label="政府补贴" prop="governmentSubsidy">
          <el-input v-model="form.governmentSubsidy" placeholder="请输入政府补贴" />
        </el-form-item>
        
        <!-- 扩展字段 -->
        <el-form-item label="业务ID" prop="businessId">
          <el-input v-model="form.businessId" placeholder="请输入业务ID" />
        </el-form-item>
        
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      
      <!-- 对话框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Management">
// 导入API接口
import { listManagement, getManagement, delManagement, addManagement, updateManagement } from "@/api/system/management"
// 导入路由
import { useRouter, useRoute } from 'vue-router'
// 导入生命周期钩子
import { onMounted, nextTick } from 'vue'
// 导入Element Plus消息组件
import { ElMessage } from 'element-plus'

// 获取当前实例
const { proxy } = getCurrentInstance()

// 响应式数据定义
const managementList = ref([]) // 入住管理列表数据
const open = ref(false) // 对话框显示状态
const loading = ref(true) // 加载状态
const showSearch = ref(true) // 搜索区域显示状态
const ids = ref([]) // 选中的ID数组
const single = ref(true) // 是否单选
const multiple = ref(true) // 是否多选
const total = ref(0) // 总记录数
const title = ref("") // 对话框标题
const daterangeCheckInStartTime = ref([]) // 入住开始时间范围
const daterangeCheckInEndTime = ref([]) // 入住结束时间范围
const componentKey = ref(1) // 组件强制刷新key

// 路由实例
const router = useRouter()
const route = useRoute()

/**
 * 跳转到入住申请表单页面
 */
const goToCheckInForm = () => {
  router.push('/system/management/checkInForm')
}

/**
 * 查看按钮操作 - 跳转到入住申请表单并传递老人信息
 * @param {Object} row - 当前行数据
 */
function handleView(row) {
  console.log("handleView 接收到的行数据:", row);
  console.log("行数据中的合同相关字段:");
  console.log("- contractNumber:", row.contractNumber);
  console.log("- contractName:", row.contractName);
  console.log("- contractStartDate:", row.contractStartDate);
  console.log("- contractEndDate:", row.contractEndDate);
  console.log("- signDate:", row.signDate);
  console.log("- partyCName:", row.partyCName);
  console.log("- partyCcontact:", row.partyCcontact);
  console.log("- contractStatus:", row.contractStatus);
  console.log("- contractFile:", row.contractFile);
  
  // 构建需要传递的老人信息参数
  const elderlyInfo = {
    // 基本信息
    elderlyId: row.elderlyId,
    name: row.elderly?.name,
    idCard: row.elderly?.idCard,
    contact: row.elderly?.contact,
    address: row.elderly?.address,
    ethnicity: row.elderly?.ethnicity,
    politicalStatus: row.elderly?.politicalStatus,
    religion: row.elderly?.religion,
    maritalStatus: row.elderly?.maritalStatus,
    education: row.elderly?.education,
    incomeSource: row.elderly?.incomeSource,
    hobbies: row.elderly?.hobbies,
    medicalInsurance: row.elderly?.medicalInsurance,
    medicalCardNo: row.elderly?.medicalCardNo,
    photo: row.elderly?.photo,
    idCardFront: row.elderly?.idCardFront,
    idCardBack: row.elderly?.idCardBack,
    
    // 入住信息
    checkInNo: row.checkInNo,
    checkInStartTime: row.checkInStartTime,
    checkInEndTime: row.checkInEndTime,
    nursingLevelId: row.nursingLevelId,
    bedId: row.bedId,
    
    // 家属信息 - 从关联数据中获取
    familyMembers: row.elderly?.familyMembers || [],
    
    // 住房情况 - 从床位信息中获取
    housingInfo: {
      bedNo: row.bed?.bedNo,
      roomNo: row.bed?.roomNo,
      buildingNo: row.bed?.buildingNo,
      floorNo: row.bed?.floorNo,
      bedType: row.bed?.bedType,
      bedStatus: row.bed?.bedStatus
    },
    
    // 合同情况 - 从入住记录中获取
    contractInfo: {
      contractNumber: row.contractNumber,
      contractName: row.contractName,
      contractStartDate: row.contractStartDate,
      contractEndDate: row.contractEndDate,
      signDate: row.signDate,
      partyCName: row.partyCName,
      partyCcontact: row.partyCcontact,
      contractStatus: row.contractStatus,
      contractFile: row.contractFile
    },
    
    // 费用信息
    feeInfo: {
      deposit: row.deposit,
      nursingFee: row.nursingFee,
      bedFee: row.bedFee,
      otherFee: row.otherFee,
      medicalInsurancePayment: row.medicalInsurancePayment,
      governmentSubsidy: row.governmentSubsidy,
      feeStartDate: row.feeStartDate,
      feeEndDate: row.feeEndDate
    },
    
    // 评估信息
    assessmentInfo: {
      selfCareScore: row.selfCareScore,
      mentalStateScore: row.mentalStateScore,
      socialParticipationScore: row.socialParticipationScore,
      totalScore: row.totalScore,
      nursingLevel: row.nursingLevel,
      assessmentDate: row.assessmentDate
    }
  }
  
  console.log("构建完成的 elderlyInfo 对象:", elderlyInfo);
  console.log("elderlyInfo.contractInfo:", elderlyInfo.contractInfo);
  console.log("contractInfo 是否为空对象:", elderlyInfo.contractInfo && Object.keys(elderlyInfo.contractInfo).length === 0);
  
  // 通过路由参数传递老人信息
  router.push({
    path: '/system/management/checkInForm',
    query: {
      elderlyInfo: JSON.stringify(elderlyInfo)
    }
  })
}


// 响应式数据对象
const data = reactive({
  // 表单数据
  form: {},
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: null,
    elderlyId: null,
    checkInStartTime: null,
    checkInEndTime: null,
    name: null,
    idCard: null,
  },
  // 表单验证规则
  rules: {
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
})

// 解构响应式数据
const { queryParams, form, rules } = toRefs(data)


/**
 * 查询入住管理列表
 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  
  // 处理入住开始时间范围参数
  if (daterangeCheckInStartTime.value && daterangeCheckInStartTime.value.length === 2) {
    queryParams.value.params["beginCheckInStartTime"] = daterangeCheckInStartTime.value[0]
    queryParams.value.params["endCheckInStartTime"] = daterangeCheckInStartTime.value[1]
  }
  
  // 处理入住结束时间范围参数
  if (daterangeCheckInEndTime.value && daterangeCheckInEndTime.value.length === 2) {
    queryParams.value.params["beginCheckInEndTime"] = daterangeCheckInEndTime.value[0]
    queryParams.value.params["endCheckInEndTime"] = daterangeCheckInEndTime.value[1]
  }
  
  console.log('开始查询入住管理列表，参数：', queryParams.value)
  
  // 调用API获取列表数据
  listManagement(queryParams.value).then(response => {
    console.log('API响应数据：', response)
    managementList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
    console.log('数据加载完成，列表长度：', managementList.value.length)
  }).catch(error => {
    console.error('获取入住管理列表失败：', error)
    ElMessage.error('获取数据失败，请重试')
    loading.value = false
  })
}

/**
 * 取消按钮操作
 */
function cancel() {
  open.value = false
  reset()
}

/**
 * 表单重置
 */
function reset() {
  form.value = {
    id: null,
    checkInNo: null,
    elderlyId: null,
    checkInStartTime: null,
    checkInEndTime: null,
    creator: null,
    createTime: null,
    nursingLevelId: null,
    bedId: null,
    feeStartDate: null,
    feeEndDate: null,
    deposit: null,
    nursingFee: null,
    bedFee: null,
    otherFee: null,
    medicalInsurancePayment: null,
    governmentSubsidy: null,
    businessId: null,
    extraField1: null,
    extraField2: null
  }
  proxy.resetForm("managementRef")
}

/**
 * 搜索按钮操作
 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/**
 * 重置按钮操作
 */
function resetQuery() {
  daterangeCheckInStartTime.value = []
  daterangeCheckInEndTime.value = []
  queryParams.value.name = null
  queryParams.value.idCard = null
  queryParams.value.contractNo = null
  proxy.resetForm("queryRef")
  handleQuery()
}

/**
 * 多选框选中数据变化处理
 * @param {Array} selection - 选中的行数据
 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/**
 * 新增按钮操作
 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加入住管理"
}

/**
 * 修改按钮操作
 * @param {Object} row - 行数据
 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getManagement(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改入住管理"
  })
}

/**
 * 提交表单
 */
function submitForm() {
  proxy.$refs["managementRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        // 修改操作
        updateManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 新增操作
        addManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/**
 * 删除按钮操作
 * @param {Object} row - 行数据
 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除入住管理编号为"' + _ids + '"的数据项？').then(function() {
    return delManagement(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/**
 * 导出按钮操作
 */
function handleExport() {
  proxy.download('system/management/export', {
    ...queryParams.value
  }, `management_${new Date().getTime()}.xlsx`)
}

/**
 * 手动刷新按钮操作
 */
function handleRefresh() {
  console.log('手动刷新数据')
  getList()
}

// 页面加载时获取列表数据
onMounted(() => {
  console.log('页面挂载，开始初始化数据加载')
  getList()
})

// 处理keep-alive缓存的activated钩子
onActivated(() => {
  console.log('组件被激活，重新加载数据')
  // 强制刷新组件
  componentKey.value++
  // 每次激活时都重新加载数据
  getList()
})

// 监听路由变化，确保每次进入页面都重新加载数据
watch(() => route.path, (newPath) => {
  if (newPath === '/system/management') {
    console.log('路由变化，重新加载数据')
    // 强制刷新组件
    componentKey.value++
    // 强制重新加载数据
    setTimeout(() => {
      getList()
    }, 50)
  }
}, { immediate: true })

// 监听路由参数变化，确保从其他页面跳转过来时也能正确加载
watch(() => route.fullPath, (newPath, oldPath) => {
  if (newPath === '/system/management' && oldPath && oldPath !== newPath) {
    console.log('从其他页面跳转过来，强制重新初始化')
    // 重置所有状态
    managementList.value = []
    loading.value = true
    componentKey.value++
    // 延迟重新加载数据
    nextTick(() => {
      getList()
    })
  }
}, { immediate: true })

// 强制重新初始化组件的方法
function forceReinitialize() {
  console.log('强制重新初始化组件')
  // 重置所有响应式数据
  managementList.value = []
  loading.value = true
  ids.value = []
  total.value = 0
  componentKey.value++
  
  // 强制重新渲染
  nextTick(() => {
    getList()
  })
}

// 暴露方法给父组件使用
defineExpose({
  forceReinitialize
})
</script>
